import Vue from 'vue'
import Router from 'vue-router'
import store from '@/system/store'
import NProgress from 'nprogress'
import { setDocumentTitle, domTitle } from '@/utils/domUtils'
import { routerMap } from './routes'
import API from '@/api'

Vue.use(Router)

const router = new Router({
    mode: 'history',
    routes: routerMap
})
store.router = router;

const whiteList = ['/auth/login', '/403', '/404']
const loginRoutePath = '/auth/login'
const defaultRoutePath = '/'
const forbiddenRoutePath = '/403'

const handleCommonUrl = (to, next, user) => {
    if (user) {
        if (to.path === loginRoutePath) {
            next({ path: defaultRoutePath })
            NProgress.done()
        }
        else if (to.meta && to.meta.permission && !to.meta.permission.includes(user.status))
            next({ path: forbiddenRoutePath })
        else next()
    }
    else {
        next({ path: loginRoutePath })
        NProgress.done()
    }
}


router.beforeEach((to, from, next) => {
    NProgress.start()
    if (to.meta && to.meta.title) setDocumentTitle(`${to.meta.title} - ${domTitle}`)
    else setDocumentTitle(`${domTitle}`)
    if (whiteList.includes(to.path)) {
        next()
    } else {
        if (store.user) {
            handleCommonUrl(to, next, store.user)
        }
        else {
            API.User.Info().then((res) => {
                if (res) {
                    store.user = res.data
                    handleCommonUrl(to, next, res.data)
                }
            })
        }
    }
})

router.afterEach(() => {
    NProgress.done()
})

export default router;
